//
//  RBUserAccountViewModel.swift
//  myWeiBo
//
//  Created by 刘邓诏初 on 16/4/13.
//  Copyright © 2016年 刘邓诏初. All rights reserved.
//

import UIKit

/// 专门处理 HMUserAccount 模型的相关操作,网络请求,字典转模型,归档,解档
class RBUserAccountViewModel: NSObject {
    
    // 单例
    static let sharedInstance = RBUserAccountViewModel()

    private override init() {
        super.init()
    }
    
    /// 账号模型，只要拿到单例就可以访问到,全局通用.
    var userAccount: RBUserAccount?
    
    
    /// 获取accessToken
    func loadAccessToken(code: String){
        // accessToken的url地址
        let urlStr = accessTokenURLString
        
        // 参数 - 字典
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : grant_type,
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        // 发送请求 ,afn.POST
        RBNetworkTool.sharedInstance.POST(urlStr, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
            
            RBPrint("授权成功 \(responseObject)")
            
            let result = responseObject as? [String : AnyObject]
            
            if let dict = result {
                // 字典转模型
                let userAccount = RBUserAccount(dic: dict)
                RBPrint("转模型成功\(userAccount)")
                
                // 将模型数据保存
                // 路径
                let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist")
                RBPrint(accountPath)
                
                // 归档
                NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
                
                
            }
            
            }) { (task, error) -> Void in
                
                RBPrint("授权失败\(error)")
        }
        
        
        
    }


}
